<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import NavBar from '@renderer/components/navBar.vue'
import SelectExportMode from '@renderer/components/selectExportMode.vue'
import useCompute from '@renderer/composables/useCompute'
import useComputeForm from '@renderer/composables/useComputeForm'
import helper from '@renderer/utils/helper'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const pageQuery = route.currentRoute.value.query
const initSubmitForm = () => ({
  cate_name: '',
  name: '',
  value: '',
  unit: '',
  main_materials: '',
  labour: '',
  auxiliary_material: '',
  remark: '',
  unit_price: '',
})
const submitForm = reactive(initSubmitForm())
const addDataDialog = ref(false)
const currentHandleType = ref('')
const currentFindIndex = ref(-1)
const selectTemplateDialog = ref(false)
const changeRow = ref<any[]>([])
const ids = ref<number[]>([])
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  addDataDialog.value = false
  await initPage()
}
const handleAddData = async () => {
  if (changeRow.value.length) {
    await handleSaveTableData(changeRow.value, 27)
    changeRow.value = []
  }
  addDataDialog.value = true
}
const handleSave = async () => {
  if (!submitForm.name) {
    ElMessage.error('请填写项目名称')
    return
  }
  if (!submitForm.unit) {
    ElMessage.error('请填写单位')
    return
  }
  if (!submitForm.value) {
    ElMessage.error('请填写数量')
    return
  }
  await addBudgetData({
    calculate_id: pageQuery.calculate_id,
    type_name: '优惠清单',
    cate_name: submitForm.cate_name,
    name: submitForm.name,
    unit: submitForm.unit,
    unit_price: submitForm.unit_price,
    main_materials: submitForm.main_materials,
    labour: submitForm.labour,
    auxiliary_material: submitForm.auxiliary_material,
    remark: submitForm.remark,
    number: submitForm.value,
  })
  handleClose()
}
const handleBlueCompute = (newVal: DiscountModel) => {
  if (!changeRow.value.includes(newVal)) {
    changeRow.value.push(newVal)
  } else {
    changeRow.value = changeRow.value.filter((item) => item !== newVal)
    changeRow.value.push(newVal)
  }
}
const handleExport = async () => {
  selectTemplateDialog.value = true
}
const handleSaveMode = async (event) => {
  handleCloseMode()
  const res = await exportFavorableTable({
    calculate_id: pageQuery.calculate_id,
    mode: event.mode,
  })
  downLoadFile(res, '优惠清单.xlsx')
}
const handleCloseMode = () => {
  selectTemplateDialog.value = false
}
const handleSaveData = async () => {
  if (!changeRow.value.length) {
    ElMessage({ type: 'success', message: '保存成功！' })
    return
  }
  await handleSaveTableData(changeRow.value, 27)
  await initPage()
  changeRow.value = []
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const handleDelData = async () => {
  if (changeRow.value.length) {
    ElMessage({ type: 'error', message: '你有未保存的数据，请先保存数据在进行删除此项目。' })
    return
  }
  if (ids.value.length) {
    await delTableData({
      calculate_id: pageQuery.calculate_id,
      ids: ids.value,
      type: 27,
    })
    await initPage()
  } else {
    ElMessage({ type: 'error', message: '请选择要删除的数据' })
  }
}
const initPage = async () => {
  await getCalculateDetail({ calculate_id: pageQuery.calculate_id })
  if (calculateInfo.value?.check_gather == 2 || !checkRule('预算明细查看权')) {
    ElMessage({ type: 'error', message: '抱歉！您没有此权限' })
    return
  }
  await getDisCountList({
    calculate_id: pageQuery.calculate_id,
    type_name: '优惠清单',
    client_type: 'GUI',
  })
  await getCalculateTableSet({ type: 5 })
}
const handleFindReplace = () => {
  window.api.openWindow('findSearch', {
    title: '备注查找与替换',
    currentWindowName: 'basiceQuipment',
    currentPage: 'discount',
  })
}
const handleFind = (content: string) => {
  const includesList = discountList
    .value!.map((item, index) => (item.remark ? (item.remark.includes(content) ? index : -1) : -1))
    .filter((index) => index !== -1)
  if (!includesList.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    return
  }
  if (currentFindIndex.value == -1) {
    currentFindIndex.value = includesList[0]
  } else {
    const currentFind = includesList.findIndex((item) => item === currentFindIndex.value)
    if (currentFind == includesList.length - 1) {
      currentFindIndex.value = includesList[0]
    } else {
      currentFindIndex.value = includesList[currentFind + 1]
    }
  }
  let handleRef = `remarkInput${discountList.value![currentFindIndex.value].id}`
  const handleRefDom = document.getElementById(handleRef)
  if (handleRefDom) handleRefDom.focus()
}
const handleAllFind = (content: string) => {
  const result = discountList.value!.filter((item) => (item.remark ? item.remark.includes(content) : false))
  if (!result.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    window.api.sendListArray(JSON.stringify([]))
    return
  }
  window.api.sendListArray(JSON.stringify(result))
}
window.api.acceptSendMsg((handleType, currentPage, content, replaceContent, ids) => {
  if (currentPage == 'discount') {
    switch (handleType) {
      case 'handleFind':
        if (currentHandleType.value == 'handleAllFind') {
          currentFindIndex.value = -1
        }
        handleFind(content)
        break
      case 'handleAllFind':
        currentFindIndex.value = -1
        handleAllFind(content)
        break
      case 'handleReplace':
      case 'handleAllReplace':
        if (ids) {
          let selectIdList = ids.split(',')
          selectIdList.forEach((idItem) => {
            const index = discountList.value!.findIndex((item) => item.id == Number(idItem))
            discountList.value![index].remark = discountList.value![index].remark.replace(content, replaceContent!)
            handleBlueCompute(discountList.value![index])
          })
        } else {
          if (currentFindIndex.value == -1) {
            ElMessage({ type: 'error', message: '抱歉！未找到匹配的数据！' })
            return
          }
          discountList.value![currentFindIndex.value].remark = discountList.value![
            currentFindIndex.value
          ].remark.replace(content, replaceContent!)
          handleBlueCompute(discountList.value![currentFindIndex.value])
          currentFindIndex.value = -1
        }
        break
    }
    currentHandleType.value = handleType
  }
})

const { discountList, getDisCountList, addBudgetData, exportFavorableTable } = useCompute()
const { downLoadFile, handleSaveTableData, checkRule } = helper()
const { getCalculateTableSet, calculateSetInfo, calculateInfo, getCalculateDetail, delTableData } = useComputeForm()
await initPage()
</script>

<template>
  <main class="bg-white flex flex-col" style="height: -webkit-fill-available">
    <div class="flex flex-1 justify-center" v-if="calculateInfo?.check_gather == 2 || !checkRule('预算明细查看权')">
      <el-empty
        image="https://cw3.obs.cn-north-4.myhuaweicloud.com/api/uploads/images/b1ed1d14709b890118b4c2b3da9114b351e11b9d.png"
        description="抱歉！您没有此权限" />
    </div>
    <section v-else class="flex flex-col overflow-hidden">
      <div class="px-6 h-[50px] border-b flex items-center bg-white" style="width: -webkit-fill-available">
        <div class="flex gap-3">
          <formButton @click="handleAddData" v-if="checkRule('预算明细修改权')">添加项目</formButton>
          <formButton @click="handleSaveData" v-if="checkRule('预算明细修改权')">保存数据</formButton>
          <formButton @click="handleDelData" v-if="checkRule('预算明细修改权') && ids.length">删除数据</formButton>
          <formButton @click="handleExport">导出</formButton>
          <formButton @click="handleFindReplace" v-if="checkRule('预算明细修改权')">查找替换</formButton>
        </div>
      </div>
      <div class="flex flex-col gap-3 p-6 pt-4 overflow-y-auto flex-1">
        <div class="flex flex-col">
          <div class="text-center font-bold text-2xl text-black mt-3 mb-1">{{ calculateSetInfo?.title }}</div>
          <div class="text-center text-sm text-[#888888]">工程地址：{{ pageQuery.calculate_name }}</div>
        </div>
        <el-table
          :data="discountList"
          border
          header-align="center"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }">
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column type="index" label="序号" align="center" width="55" />
          <el-table-column prop="name" label="名称" align="center" width="180">
            <template #default="scope">
              <el-input
                v-model="scope.row.name"
                v-if="checkRule('预算明细修改权')"
                @input="handleBlueCompute(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" align="center" width="80">
            <template #default="scope">
              <el-input
                v-model="scope.row.unit"
                v-if="checkRule('预算明细修改权')"
                @input="handleBlueCompute(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="number" label="数量" align="center" width="92">
            <template #default="scope">
              <el-input
                v-model="scope.row.number"
                v-if="checkRule('预算明细修改权')"
                type="number"
                @mousewheel.native.prevent
                @input="handleBlueCompute(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                :id="`remarkInput${scope.row.id}`"
                v-if="checkRule('预算明细修改权')"
                @input="handleBlueCompute(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </section>
    <el-dialog v-model="addDataDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="新增项目数据" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6" label-width="90">
          <el-form-item label="项目名称:" required>
            <el-input v-model="submitForm.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="单位:" required>
            <el-input v-model="submitForm.unit" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="数量:" required>
            <el-input
              v-model="submitForm.value"
              placeholder="请输入"
              clearable
              type="number"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="submitForm.remark" placeholder="请输入" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <SelectExportMode
      :selectTemplateDialog="selectTemplateDialog"
      openCate="优惠清单导出模板"
      @handleSaveMode="handleSaveMode"
      @handleCloseMode="handleCloseMode" />
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
  flex: 1;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
